<?php

namespace app\api\model;

use think\Db;
use think\Model;

class UserPayment extends Model
{
    protected $hidden = ['updatetime', 'deletetime', 'status', 'service'];

    public function getCreateTimeAttr($value)
    {
        return $value ? date('Y-m-d H:i', $value) : '';
    }

    public function services()
    {
        return $this->hasMany(UserPaymentService::class, 'user_payment_id', 'id');
    }

    /**
     * 用户买单记录
     */
    public static function getByUserId($userId)
    {
        return self::with(['services'])->where('user_id', $userId)->where('status', 1)->order("createtime desc")->select();
    }

    /**
     * 创建订单
     */
    public static function createOrder($data, $service)
    {
        $userPaymentService = new UserPaymentService();
        Db::startTrans();
        try {
            $order = self::create($data);
            if ($service) {
                $totalAmount = $userPaymentService->add($order->id, $service);
                $order->total_amount = $totalAmount;
                $order->save();
            }
            Db::commit();
            return $order;
        } catch (\Exception $e) {
            Db::rollback();
            return $e->getMessage();
        }
    }

}
